'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {

    async create() {
        const { ctx, service } = this;
        const rule = {
            mobile: { type: 'string', required: true, allowEmpty: false, format: /^[0-9]{11}$/ },
            password: { type: 'password', required: true, allowEmpty: false, min: 6 },
        };
        const payload = ctx.request.body || {}
        let errs = this.app.validator.validate(rule, payload);
        if (errs !== undefined) {
            const err = {err: errs};
            ctx.helper.failure({ ctx, err });
            return;
        }
        const res = await service.user.create(payload);
        ctx.helper.success({ ctx, res });
    }

    async login() {
        const { ctx, service } = this
        const rule = {
            mobile: { type: 'string', required: true, allowEmpty: false, format: /^[0-9]{11}$/ },
            password: { type: 'password', required: true, allowEmpty: false, min: 6 },
        };
        const payload = ctx.request.body || {}
        let errs = this.app.validator.validate(rule, payload);
        if (errs !== undefined) {
            const err = {err: errs};
            ctx.helper.failure({ ctx, err });
            return;
        }
        const res = await service.user.login(payload)
        ctx.helper.success({ ctx, res })
    }

    async update() {
        const { ctx, service } = this;
        const rule = {
            name: { type: 'string', required: false },
            birthday: { type: 'date', required: false },
            gender: { type: 'int', required: false },
            avatar: { type: 'string', required: false },
        };
        let errs = this.app.validator.validate(rule, ctx.request.body);
        if (errs !== undefined) {
            const err = {err: errs};
            ctx.helper.failure({ ctx, err });
            return;
        }
        const payload = ctx.request.body || {};
        const res = await service.user.update(payload);
        ctx.helper.success({ ctx, res });
    }

    async resetPsw() {
        
    }
}

module.exports = UserController;